<?php
/**
 * Created by jinqiang on 2024/9/5 17:15.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Soa;


use App\Http\Models\Mysql\SsyJstPurchaseinOrderEmbroideryCountTable;
use App\Http\Models\Mysql\SsyPricingExamineTable;
use App\Http\Models\Mysql\SsyProcessingListTable;
use App\Http\Models\Mysql\VerifyPriceTable;
use App\Http\Repository\ApprovalRepository;

class CyStatisticService
{
    public function search($param)
    {
        $conn = (new SsyJstPurchaseinOrderEmbroideryCountTable())->where('r_years', $param['date']);
        if(isset($param['status']) && $param['status'] != ""){
            $conn = $conn->where('status', (Int)$param['status']);
        }
        if($param['brand_code'] ?? ""){
            $conn = $conn->where('brand_code', $param['brand_code']);
        }
        if($param['supplier_id'] ?? ""){
            $conn = $conn->where('supplier_id', $param['supplier_id']);
        }
        if($param['embroidery_factory_id'] ?? ""){//绣花厂id
            $conn = $conn->where('embroidery_factory_id', $param['embroidery_factory_id']);
        }
        if($param['processing_code'] ?? ""){
            $conn = $conn->where('processing_code', 'like', $param['processing_code']."%");
        }
        if($param['exclude_fc'] ?? ""){//排除返修加工单
            $conn = $conn->where('processing_code', 'not like', "FC%");
        }
        $res = $conn->whereNotNull('po_id')->whereNotNull('factory_name')->whereNotNull('type_no')->paginate((Int)$param['limit'])->toArray();
        $processingCodes = array_column($res['data'], 'processing_code');
        $examineOrders = [];//获取核价审核未提交的数据
        if(!empty($processingCodes)){
            $examineList = (new SsyPricingExamineTable())->whereIn('processing_code', $processingCodes)->where('status', 0)->get(['processing_code'])->toArray();
            $examineOrders = array_column($examineList, 'processing_code');
        }
        foreach($res['data'] as &$item){
            $item['pricing_examine_status'] = in_array($item['processing_code'], $examineOrders) ? 0 : 1;
        }
        unset($item);
        return ['data' => $res['data'], 'total' => $res['total']];
    }

    public function submit($processingCodes)
    {
        $processingList = (new SsyProcessingListTable())->whereIn('processing_code', $processingCodes)->groupBy(['processing_code','verify_price_number'])
            ->get(['processing_code','verify_price_number'])->toArray();
        $priceNumbers = array_column($processingList, 'processing_code', 'verify_price_number');
        $verifyPriceList = (new VerifyPriceTable())->whereIn('number', array_keys($priceNumbers))->get()->toArray();
        $verifyPriceMap = array_column($verifyPriceList, null, 'number');
        $pricingExamines = (new SsyPricingExamineTable())->whereIn('processing_code', array_values($priceNumbers))->where('status', 0)->get()->toArray();
        $pricingExamineMap = array_column($pricingExamines, null, 'processing_code');
        if(count($pricingExamines) != count($processingCodes)){
            return ['code' => -1, 'msg' => '提交失败: 部分核价审核状态已提交, 无需重复提交'];
        }
        if(count($verifyPriceList) != count($processingCodes)){
            return ['code' => -1, 'msg' => '提交失败: 部分加工单大货核价不存在'];
        }
        $garmentCostPlusTotal = [];//成衣成本加价总价
        $costPlusTotal = [];//成本加价总价
        foreach ($verifyPriceMap as $priceNumber => $order){
            $processingCode = $priceNumbers[$priceNumber];
            if(empty($order['f65'])){
                $garmentCostPlusTotal[] = $processingCode;
            }
            if(empty($order['f67'])){
                $costPlusTotal[] = $processingCode;
            }
        }
        if(!empty($garmentCostPlusTotal)){
            return ['code' => -1, 'msg' => '成衣成本加价总价为空, 加工单号: '.implode(',', $garmentCostPlusTotal)];
        }
        if(!empty($costPlusTotal)){
            return ['code' => -1, 'msg' => '成本加价总价为空, 加工单号: '.implode(',', $costPlusTotal)];
        }
        $user = auth()->guard("api")->user()->toArray();
        foreach ($verifyPriceMap as $priceNumber => $order){
            $processingCode = $priceNumbers[$priceNumber];
            $save = [
                'pay_process_price' => $order['f65'],//成衣成本加价总价--实付
                'pay_pricing_price' => $order['f67'],//成本加价总价--实付
                'process_pricing_price' => $order['f65'],//成衣成本加价总价--大货
                'big_pricing_price' => $order['f67'],//成本加价总价--大货
                'difference_price' => 0,
                'reason' => '',
                'remarks' => '加工单无核价异动',
                'pay_pricing_number' => $priceNumber,
                'source_type' => 2,
                'pay_float_type' => 1,
                'pay_float' => 0,
                'pay_float_lv' => 0,
                'addtime' =>date("Y-m-d H:i:s"),
                'status' => 2,
                'examinetime' => date("Y-m-d H:i:s")
            ];
            $examineObj = array_merge($pricingExamineMap[$processingCode], $save);
            //$res = ApprovalRepository::addFlowPricing($examineObj, $user);
            //更新回货统计表 实付价
            $res = ApprovalRepository::setReturnsPrice($examineObj, 2);
            if($res['code'] !== 0){
                return $res;
            }
            (new SsyPricingExamineTable())->updateData($examineObj['id'], $save);
        }
        return ['code' => 0, 'msg' => '提交成功'];
    }
}
